//
//  MAFunctionViewController.m
//  meiang_edu
//
//  Created by Liubi_Chaos_G on 2018/7/30.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAFunctionViewController.h"

#import "MAChildViewController.h"
#import "ChaosLabel.h"
#import "MAJiGouModel.h"
#import "MAFuncCollectionCell.h"
#import "MAFuncListViewController.h"
#import "MAScanViewController.h"
#import "MANavigationController.h"
#import "MAAuthorViewController.h"
#import "MALoginViewController.h"
#import "MATabBarViewController.h"

#define ChaosLabelW 70
#define FuncCollectionCell @"FuncCollectionCell"

@interface MAFunctionViewController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UIView *sdCycleContainerView;

@property (weak, nonatomic) IBOutlet UIScrollView *titleScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
/** indicator */
@property(nonatomic,strong) UIImageView *indicator;

/** collectionView */
@property(nonatomic,strong) UICollectionView *collectionView;

/** jigouModels */
@property(nonatomic,strong) NSMutableArray *jigouModels;

@end

@implementation MAFunctionViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self hiddenTabbar:NO];
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    if (!userinfo.token && userinfo.token.length == 0)
    {
        // 登录
        MALoginViewController *vc = [[MALoginViewController alloc] init];
        MANavigationController *nav1 = [[MANavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:nav1 animated:YES completion:^{
        }];
    }
    else
    {
        if (self.jigouModels.count)
        {
            [self.collectionView reloadData];
        }
        else
        {
            [self setupBasic];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginBackButtonClick) name:@"loginButtonClick" object:nil];
}

- (void)loginBackButtonClick
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = [[MATabBarViewController alloc] init];
    window.rootViewController = vc;
}

- (void)setupBasic {
    self.title = @"功能";
    
    [self wr_setNavBarBackgroundAlpha:0];
    
    [self.sdCycleContainerView addSubview:self.collectionView];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([MAFuncCollectionCell class]) bundle:nil] forCellWithReuseIdentifier:FuncCollectionCell];
    
    [self requestJiGouData];
}


- (void)requestJiGouData {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",USER_ORGANIZATION_LIST,userinfo.ID];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.jigouModels = [MAJiGouModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            
            if (self.jigouModels.count) {
                MAJiGouModel *model = [self.jigouModels firstObject];
                [[NSNotificationCenter defaultCenter] postNotificationName:kMAChangeJiGouNotification object:nil userInfo:@{@"jigou_id" : model.ID}];
            }
            
            [self.collectionView reloadData];
            
            [self setupChildVC];
            // 添加标题
            [self setupTitle];
            
            if (self.jigouModels.count) {
                MAJiGouModel *model = self.jigouModels[0];
                
                [self controlTitleScrollView:model];
            }
            
            // 添加指示器
            [self setupIndicator];
            
            // 默认显示第0个子控制器
            [self scrollViewDidEndScrollingAnimation:self.contentScrollView];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupIndicator {
    UIImageView *indicator = [[UIImageView alloc] initWithImage:[UIImage imageWithColor:[UIColor blueColor]]];
    
    indicator.width = ChaosLabelW;
    indicator.height = 5;
    indicator.x = 0;
    indicator.y = self.titleScrollView.height - 5;
    indicator.contentMode = UIViewContentModeCenter;
    
    [self.view addSubview:indicator];
    self.indicator = indicator;
}

/**
 * setupChildVc
 */
- (void)setupChildVC
{
    MAFuncListViewController *vc5 = [[MAFuncListViewController alloc] init];
    vc5.title = @"功能";
    vc5.model = [self.jigouModels firstObject];
    [self addChildViewController:vc5];
    
    MAChildViewController *vc1 = [[MAChildViewController alloc] init];
    vc1.title = @"动态";
    vc1.jigouModel = [self.jigouModels firstObject];
    [self addChildViewController:vc1];
    
    MAChildViewController *vc2 = [[MAChildViewController alloc] init];
    vc2.title = @"资质";
    vc2.jigouModel = [self.jigouModels firstObject];
    [self addChildViewController:vc2];
    
    MAChildViewController *vc3 = [[MAChildViewController alloc] init];
    vc3.title = @"员工";
    vc3.jigouModel = [self.jigouModels firstObject];
    [self addChildViewController:vc3];
    
    MAChildViewController *vc4 = [[MAChildViewController alloc] init];
    vc4.title = @"留言板";
    vc4.jigouModel = [self.jigouModels firstObject];
    [self addChildViewController:vc4];
}

/**
 * 添加标题
 */
- (void)setupTitle
{
    // 定义临时变量
    CGFloat labelW = 64;
    CGFloat labelY = 0;
    CGFloat labelH = self.titleScrollView.frame.size.height;
    NSInteger count = self.childViewControllers.count;
    // 添加label
    for (NSInteger i = 0; i<count; i++) {
        ChaosLabel *label = [[ChaosLabel alloc] init];
        label.text = [self.childViewControllers[i] title];
        CGFloat labelX = i * labelW;
        label.frame = CGRectMake(labelX, labelY, labelW, labelH);
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)]];
        label.tag = i;
        label.lineView.hidden = YES;
        
        [self.titleScrollView addSubview:label];
        
        if (i == 0) { // 最前面的label
            label.scale = 1.0;
        }
    }
    
    // 设置contentSize
    self.titleScrollView.contentSize = CGSizeMake(count * labelW, 0);
    self.contentScrollView.contentSize = CGSizeMake(count * [UIScreen mainScreen].bounds.size.width, 0);
}

/**
 * 监听顶部label点击
 */
- (void)labelClick:(UITapGestureRecognizer *)tap
{
    // 取出被点击label的索引
    NSInteger index = tap.view.tag;
    
    // 让底部的内容scrollView滚动到对应位置
    CGPoint offset = self.contentScrollView.contentOffset;
    offset.x = index * self.contentScrollView.frame.size.width;
    [self.contentScrollView setContentOffset:offset animated:YES];
    
}
#pragma mark - <UIScrollViewDelegate>
/**
 * scrollView结束了滚动动画以后就会调用这个方法（比如- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;方法执行的动画完毕后）
 */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    // 一些临时变量
    CGFloat width = scrollView.frame.size.width;
    CGFloat height = scrollView.frame.size.height;
    CGFloat offsetX = scrollView.contentOffset.x;
    
    // 当前位置需要显示的控制器的索引
    NSInteger index = offsetX / width;
    
    // 指示器移动
    NSInteger count = self.childViewControllers.count;
    CGFloat indicatorW = SCREEN_WIDTH / count;
    [UIView animateWithDuration:0.25 animations:^{
        self.indicator.x = indicatorW * index;
    }];
    
    // 让对应的顶部标题居中显示
    ChaosLabel *label = self.titleScrollView.subviews[index];
    CGPoint titleOffset = self.titleScrollView.contentOffset;
    titleOffset.x = label.center.x - width * 0.5;
    // 左边超出处理
    if (titleOffset.x < 0) titleOffset.x = 0;
    // 右边超出处理
    CGFloat maxTitleOffsetX = self.titleScrollView.contentSize.width - width;
    if (titleOffset.x > maxTitleOffsetX) titleOffset.x = maxTitleOffsetX;
    
//    [self.titleScrollView setContentOffset:titleOffset animated:YES];
    // 让其他label回到最初的状态
    for (ChaosLabel *otherLabel in self.titleScrollView.subviews) {
        if (otherLabel != label) {
            otherLabel.scale = 0.0;
        }
    }
    
    // 取出需要显示的控制器
    UIViewController *willShowVc = self.childViewControllers[index];
    
    // 如果当前位置的位置已经显示过了，就直接返回
    if ([willShowVc isViewLoaded]) return;
    
    // 添加控制器的view到contentScrollView中;
    willShowVc.view.frame = CGRectMake(offsetX, 0, width, height);
    [scrollView addSubview:willShowVc.view];
}

/**
 * 手指松开scrollView后，scrollView停止减速完毕就会调用这个
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        
        // 一些临时变量
        CGFloat width = scrollView.frame.size.width;
        CGFloat offsetX = scrollView.contentOffset.x;
        
        // 当前位置需要显示的控制器的索引
        NSInteger index = offsetX / width;
        
        if (self.jigouModels.count) {
            MAJiGouModel *model = self.jigouModels[index];
            
            [self controlTitleScrollView:model];

            // 向子控制器传递数据
            for (UIViewController *vc in self.childViewControllers) {
                if ([vc isKindOfClass:[MAChildViewController class]]) {
                    MAChildViewController *childVC = (MAChildViewController *)vc;
                    childVC.jigouModel = model;
                }
                if ([vc isKindOfClass:[MAFuncListViewController class]]) {
                    MAFuncListViewController *childVC = (MAFuncListViewController *)vc;
                    childVC.model = model;
                }
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kMAChangeJiGouNotification object:nil userInfo:@{@"jigou_id" : model.ID}];
        }
        return;
    }
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

/**
 * 只要scrollView在滚动，就会调用
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        return;
    }
    // 一些临时变量
    CGFloat width = scrollView.frame.size.width;
    CGFloat offsetX = scrollView.contentOffset.x;
    
    // 当前位置需要显示的控制器的索引
    CGFloat index = offsetX / width;
    
    // 指示器移动
    NSInteger count = self.childViewControllers.count;
    CGFloat indicatorW = SCREEN_WIDTH / count;
    [UIView animateWithDuration:0.25 animations:^{
        self.indicator.x = indicatorW * index;
    }];
    
    CGFloat scale = scrollView.contentOffset.x / scrollView.frame.size.width;
    if (scale < 0 || scale > self.titleScrollView.subviews.count - 1) return;
    
    // 获得需要操作的左边label
    NSInteger leftIndex = scale;
    ChaosLabel *leftLabel = self.titleScrollView.subviews[leftIndex];
    
    // 获得需要操作的右边label
    NSInteger rightIndex = leftIndex + 1;
    ChaosLabel *rightLabel = (rightIndex == self.titleScrollView.subviews.count) ? nil : self.titleScrollView.subviews[rightIndex];
    
    // 右边比例
    CGFloat rightScale = scale - leftIndex;
    // 左边比例
    CGFloat leftScale = 1 - rightScale;
    
    // 设置label的比例
    leftLabel.scale = leftScale;
    rightLabel.scale = rightScale;
}

- (void)controlTitleScrollView:(MAJiGouModel *)model {
    if ([model.ortype isEqualToString:@"family"]) { // 家庭,需要隐藏某些标签
        for (int i=0; i<self.titleScrollView.subviews.count; i++) {
            ChaosLabel *label = (ChaosLabel *)self.titleScrollView.subviews[i];
            if (![label.text isEqualToString:@"功能"]) { // 不是功能标签页  都要隐藏
                label.hidden = YES;
                [self.contentScrollView setContentOffset:CGPointZero animated:YES];
                self.contentScrollView.scrollEnabled = NO;
            }
        }
    } else {
        
        for (int i=0; i<self.titleScrollView.subviews.count; i++) {
            ChaosLabel *label = (ChaosLabel *)self.titleScrollView.subviews[i];
            label.hidden = NO;
            //                    [self.contentScrollView setContentOffset:CGPointZero animated:YES];
            self.contentScrollView.scrollEnabled = YES;
        }
    }
}

#pragma mark - collectionViewDelegate & datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.jigouModels.count;
}

//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MAFuncCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:FuncCollectionCell forIndexPath:indexPath];
    MAJiGouModel *model = self.jigouModels[indexPath.item];
    cell.model = model;
    return cell;
}

#pragma mark - getter & setter
- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.itemSize = CGSizeMake(SCREEN_WIDTH, 226);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 226) collectionViewLayout:layout];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
    }
    return _collectionView;
}

- (NSMutableArray *)jigouModels {
    if (_jigouModels == nil) {
        _jigouModels = [NSMutableArray array];
    }
    return _jigouModels;
}
@end
